package com.huxiu;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.holder.WoFaBiaoHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.HuaTiItem;
import com.huxiu.net.responses.HuaTiListDataResponse;
import com.huxiu.utils.Global;
import com.huxiu.utils.LogUtil;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class WoFaBiaoActivity extends BaseActivity {
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.listview_wofanbiao)
    private RefreshListView list;
    @ViewInject(R.id.back)
    private ImageView back;

    @ViewInject(R.id.nothing_ll)
    private LinearLayout nothing_ll;
    @ViewInject(R.id.nothing_text)
    private TextView nothing_text;

    private String typeStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wofabiao);
        ViewUtils.inject(this);
        typeStr = getIntent().getStringExtra("type");
        if ("wofabiao".equals(typeStr)) {
            title.setText("我发表的话题");
        } else {
            title.setText("我回复的话题");
        }
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        list.setOnRefreshingListener(new MyOnRefreshingListener());
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer();
            }
        });
    }

    private boolean isRefresh = false;// 当前是否是下拉刷新
    private boolean isLoadMore = false;// 当前是否是加载更多

    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage < totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                isLoadMore = false;
                list.loadMoreFinished();
                //                Utils.showToast(R.string.no_more);
                Toast.makeText(WoFaBiaoActivity.this, R.string.no_more, Toast.LENGTH_SHORT).show();

            }
        }

    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(1);
    }

    private int currentPage = 0;
    private int totalPages = 0;
    MyAdapter adapter;
    private List<HuaTiItem> lists = new ArrayList<>();

    //获取推荐页列表页数据
    private void loadList(final int page) {
        String url = "";
        if ("wofabiao".equals(typeStr)) {
            url = NetworkConstants.MY_THREAD_CREATE_URL;
        } else {
            url = NetworkConstants.MY_THREAD_COMMENT_URL;
        }
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("uid", Global.user.uid);
        //        params.put("uid", "290388");
        GsonRequest<HuaTiListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                HuaTiListDataResponse.class, false, params,
                new Response.Listener<HuaTiListDataResponse>() {
                    @Override
                    public void onResponse(HuaTiListDataResponse response) {
                        if (response.isSuccess()) {
                            if (response.data.total == 0) {
                                nothing_ll.setVisibility(View.VISIBLE);
                                if ("wofabiao".equals(typeStr)) {
                                    nothing_text.setText(R.string.no_publish_text);
                                } else {
                                    nothing_text.setText(R.string.no_reply_text);
                                }
                            } else {
                                nothing_ll.setVisibility(View.GONE);
                                if (page == 1) {
                                    lists.clear();
                                }
                                Collections.addAll(lists, response.data.datalist);
                                currentPage = response.data.cur_page;
                                totalPages = response.data.total_page;
                                parseListJson();
                                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                                if (isRefresh) {
                                    list.refreshFinished(true);
                                    isRefresh = false;
                                } else if (isLoadMore) {
                                    list.loadMoreFinished();
                                    isLoadMore = false;
                                }
                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                Utils.showToast(R.string.generic_failure);
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson() {
        if (!isLoadMore) {
            adapter = new MyAdapter();
            list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            LogUtil.i("qcl3", "" + lists.size());
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            WoFaBiaoHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(WoFaBiaoActivity.this, R.layout.item_wofabiao_list, null);
                holder = new WoFaBiaoHolder(view, WoFaBiaoActivity.this);
                view.setTag(holder);
            }
            holder = (WoFaBiaoHolder) view.getTag();
            HuaTiItem item = lists.get(position);
            holder.setAdapter(adapter);
            holder.bindItem(item);//这里用来把获取到的数据传递给holder
            return view;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
